﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class GetTreeMenuHandler : IRequestHandler<GetTreeMenuCommand, ApiResult<List<TreeMenuDTO>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public GetTreeMenuHandler(IBaseRepository<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<TreeMenuDTO>>> Handle(GetTreeMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<TreeMenuDTO>> res = new ApiResult<List<TreeMenuDTO>>();
            res.Code = ApiEnum.Success;
            res.Msg = "显示树形成功";
            res.Data = GetTree(0);
            return Task.FromResult(res);
        }
        private List<TreeMenuDTO> GetTree(int pid)
        {
            var info = menuRepo.GetAll().Where(x => x.Pid == pid).ToList();
            var model=mapper.Map<List<TreeMenuDTO>>(info);
            foreach (var item in model)
            {
                item.children = GetTree(item.Id);
            }
            return model;
        }
    }
}
